//
//  statusPictureView.swift
//  MicroBlog
//
//  Created by QT on 15/8/3.
//  Copyright © 2015年 綦敦涛. All rights reserved.
//

import UIKit
import SDWebImage
private let statusPictureCellID = "statusPictureView"
let HMPictureViewNotificationInfoIndexPath = "HMPictureViewNotificationInfoIndexPath"
let HMPictureViewNotificationInfoURL = "HMPictureViewNotificationInfoURL"
let HMpictureViewNotification = "HMpictureViewNotification"


class statusPictureView: UICollectionView {
    
    var PictureStatus: status?{
        didSet{
            sizeToFit()
            reloadData()
            
//            print(PictureStatus.)
            
//            let key = PictureStatus!.pic_URL![indexpath.item].absoluteString
            //        let pic = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)

            
        }
    }
    
    private let pictureLayout = UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
        
        // prepareUI
        backgroundColor = UIColor.clearColor()
        
        
        // 注册cell
        registerClass(statusPictureCell.self, forCellWithReuseIdentifier: statusPictureCellID)
        
        // 设置数据源
        self.dataSource = self
        self.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func sizeThatFits(size: CGSize) -> CGSize {
        return getPictureSize()
    }

    func getPictureSize() -> CGSize{
        // 确定每张图片大小
        let picSize = CGSize(width: 90, height: 90)
        // margin
        let margin: CGFloat  = 10
        // 设置itemSize
        pictureLayout.itemSize = picSize
        // 每行最多显示数量
        let rowCount = 3
        // 图片数量
        let count = PictureStatus?.pic_URL?.count ?? 0
        /**
        *  设置视图尺寸
        */
        if count == 0{
            return CGSizeZero
        }
        if count == 1{
//            let size = CGSize(width: 150, height: 80)
//            pictureLayout.itemSize = size
//            print(size)
            let urlString = PictureStatus?.pic_URL![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
            
            var size = image.size
            
            if image == nil{
                size = CGSize(width: 150, height: 80)
            }
            
            size.width = size.width < 40 ? 40 : size.width
            size.height = size.height > UIScreen.mainScreen().bounds.height ? 150 : size.height
            return size
            
        }
        if count == 4{
            let w = picSize.width * 2.0 + margin
            return CGSize(width: w, height: w)
        }
        
        // 其他情况
        /*
        1.根据图片数量，计算需要显示的行数
           2,3
           5,6
           7,8,9
        */
        
        let rows = (count-1) / rowCount  + 1
        let w = picSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1 )*margin
        let h = picSize.height * CGFloat(rows) + CGFloat(rows - 1) * margin
        return CGSize(width: w, height: h)
    }
    
    // MARK: -获取缩略图在窗口的位置
    func getSmallPicFrame(indexpath: NSIndexPath) ->CGRect{
        let cell = self.cellForItemAtIndexPath(indexpath)!
        return convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
//    // MARK: -获取全屏位置
    func getFullScreenSize(indexpath: NSIndexPath) ->CGRect{
        // 1.获取缓存图片
          let key = PictureStatus!.pic_URL![indexpath.item].absoluteString
          let pic = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        // 2.获取高度
          let scale = pic.size.height / pic.size.width
          let h = UIScreen.mainScreen().bounds.width * scale
        // 3.判断长短图
        var y: CGFloat = 0
        if h < UIScreen.mainScreen().bounds.height{
            // 短图
            y = ( UIScreen.mainScreen().bounds.height - h ) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: UIScreen.mainScreen().bounds.width, height: h)
    }
}


extension statusPictureView : UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print(PictureStatus?.largePic_URL)
        // MARK: - 通知
//        // 注册通知
        NSNotificationCenter.defaultCenter().postNotificationName(HMpictureViewNotification, object: self, userInfo: [HMPictureViewNotificationInfoURL: PictureStatus!.largePic_URL!,HMPictureViewNotificationInfoIndexPath:indexPath])
        
        
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return (PictureStatus?.pic_URL?.count) ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureCellID, forIndexPath: indexPath) as! statusPictureCell
        cell.imgUrl = PictureStatus?.pic_URL![indexPath.item]
        
        return cell
    }
}


// 自定义cell
class statusPictureCell : UICollectionViewCell{
    
    var imgUrl: NSURL?{
        didSet{
            picView.sd_setImageWithURL(imgUrl)
            gifView.hidden = imgUrl?.absoluteString.lowercaseString.pathExtension != "gif"
            
            
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI(){
        contentView.addSubview(picView)
        picView.ff_Fill(contentView)
        // 添加gif标记
        picView.addSubview(gifView)
        // 布局gifView
        gifView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: picView, size: nil)
    }
    
    
    //懒加载
    private lazy var picView: UIImageView = {
        let pic = UIImageView()
        pic.contentMode = UIViewContentMode.ScaleAspectFill
        pic.clipsToBounds = true
           return pic
}()
    
    // 懒加载gif
    private lazy var gifView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}


